﻿using log4net;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using TruckScale.Helpers;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Views
{
  /// <summary>
  /// Interaction logic for DMSpareView.xaml
  /// </summary>
  public partial class DMSpareView : RadWindow, INotifyPropertyChanged
  {
    //log
    private static readonly log4net.ILog log = LogManager.GetLogger("DMSpareView");
    //新增后同步刷新列表
    public event PropertyChangedEventHandler PropertyChanged;
    public string InfoBar { get; set; }
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public ObservableCollection<SpareModel> SpareList { get; set; }
    public SpareModel SelectedSpare { get; set; }
    public DMSpareView()
    {
      InitializeComponent();
      this.DataContext = this;
      SpareList = new ObservableCollection<SpareModel>(SpareModel.SelectSpare());

      List<string> itemList = WeighFormModel.SelectActiveField()
        .Where(wf => wf.WeighFormKey.StartsWith("_by"))
        .Select(wf => wf.WeighFormValue).ToList();
      ((GridViewComboBoxColumn)this.radGridView.Columns["SpareName"]).ItemsSource = itemList;
    }

    private void RadGridView_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
    {
      //做保存动作时先清空消息栏里之前的提示
      InfoBar = string.Empty;

      //通过【取消】结束编辑时，删掉选中的编辑行
      if (e.EditAction == GridViewEditAction.Cancel)
      {
        SpareList.Remove((SpareModel)e.EditedItem);
        return;
      }

      //结束编辑时，有错误，返回
      if (e.UserDefinedErrors.Count > 0)
      {
        return;
      }

      SpareModel spare = e.Row.DataContext as SpareModel;
      spare.SpareKey = WeighFormModel.SelectActiveField().FirstOrDefault(wf => wf.WeighFormValue == spare.SpareName)?.WeighFormKey;
      //根据是否有AutoNo判断是新增还是更新
      if (spare.AutoNo == null)
      {
        if (0 < SpareModel.InsertSpare((SpareModel)e.EditedItem))
        {
          //新增完成后重载列表，将数据库中自动生成的id也读取出来
          SpareList = new ObservableCollection<SpareModel>(SpareModel.SelectSpare());

          InfoBar = $"新增备用字段 {spare.SpareName} : {spare.SpareValue}";
          SetLog(InfoBar, LogType.OperationLogger);
        }
        else
        {
          InfoBar = $"新增备用字段失败";
        }
      }
      else
      {
        if (0 < SpareModel.UpdateSpare((SpareModel)e.EditedItem))
        {
          InfoBar = $"修改备用字段 {spare.SpareName}";

          SetLog(InfoBar, LogType.OperationLogger);
        }
        else
        {
          InfoBar = $"修改备用字段失败";
        }
      }
    }

    private void RadGridView_RowValidating(object sender, GridViewRowValidatingEventArgs e)
    {
      SpareModel spare = e.Row.DataContext as SpareModel;
      if (spare.SpareName == null)
      {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "SpareName";
        validationResult.ErrorMessage = "字段名称不能为空";
        e.ValidationResults.Add(validationResult);
        e.IsValid = false;
      }
      if (spare.SpareValue == null)
      {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "SpareValue";
        validationResult.ErrorMessage = "字段值不能为空";
        e.ValidationResults.Add(validationResult);
        e.IsValid = false;
      }
      if (SpareModel.SelectSpareField(spare.SpareKey) > 0 && spare.AutoNo == null)
      {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "SpareKey";
        validationResult.ErrorMessage = "当前字段已使用公式，无法重复添加";
        e.ValidationResults.Add(validationResult);
        e.IsValid = false;
      }
    }

    private void RadGridView_Deleting(object sender, GridViewDeletingEventArgs e)
    {
      foreach (SpareModel spare in e.Items)
      {
        var ret = SpareModel.DeleteSpare(spare);
        if (ret > 0)
        {
          InfoBar = $"备用字段已删除";
          SetLog(InfoBar, LogType.OperationLogger);
        }
        else if (ret < 0)
        {
          InfoBar = $"删除失败，请查看系统日志！";
        }
        return;
      }
    }

  }
}
